package com.simoniu.first.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.PushBuilder;
import java.io.IOException;

/**
 * 将用户所需的WEB资源提前推送到用户的浏览器缓存中，当用户使用浏览器访问所需WEB资源时，
 * 用户不需要再次下载所需的资源，因为用户所需的WEB资源已经存在与用户的浏览器缓存中。
 */
@WebServlet("/PushServlet")
public class PushServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PushBuilder pushBuilder = req.newPushBuilder();

        if (pushBuilder != null) {
            PushBuilder path = pushBuilder.path("./images/hello.jpg");
            path.push();

            // 只推送最后一个path里的资源
            //PushBuilder path = pushBuilder.path("./hey.jpg").path("./hello.jpg");
            //path.push();

            // 推送多个资源的写法
            //pushBuilder.path("./hello.jpg").push();
            //pushBuilder.path("./hey.jpg").push();
        }

        req.getRequestDispatcher("test.html").forward(req, resp);

    }
}
